#!/usr/bin/env bash
set -e

# 1. 计算脚本所在目录和备份目录
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKUP_DIR="$SCRIPT_DIR/../backups"
mkdir -p "$BACKUP_DIR"

# 2. 自动取卷名前缀（docker-compose 项目名=目录名）
PROJECT_ROOT=$(realpath "$SCRIPT_DIR/..")
PROJECT_NAME=$(basename "$PROJECT_ROOT")

MYSQL_VOL="${PROJECT_NAME}_mysql_data"
REDIS_VOL="${PROJECT_NAME}_redis_data"

# 3. 导出
echo "=> 导出 $MYSQL_VOL ..."
docker run --rm \
  -v "$MYSQL_VOL:/vol" \
  -v "$BACKUP_DIR:/backup" alpine \
  tar czf "/backup/${MYSQL_VOL}.tar.gz" -C /vol .

echo "=> 导出 $REDIS_VOL ..."
docker run --rm \
  -v "$REDIS_VOL:/vol" \
  -v "$BACKUP_DIR:/backup" alpine \
  tar czf "/backup/${REDIS_VOL}.tar.gz" -C /vol .

echo "完成！文件已生成："
ls -lh "$BACKUP_DIR"/*.tar.gz